package com.shy.springframework.beans.factory.support;

import com.shy.springframework.beans.BeansException;
import com.shy.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 构造函数方式创建实例
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {

        Class clazz = beanDefinition.getBeanClass();
            try {
                if (null != ctor){
                    return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
                }else {
                    return clazz.getDeclaredConstructor().newInstance();
                }
            } catch (InstantiationException|IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
                throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
            }
    }
}
